package com.klikmee.sms.core.base.communicator.starion;

import java.io.IOException;
import java.text.MessageFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.HttpRequestHandler;

/**
 * Component responsible for handling starion's http notification requests.
 * After request is received, SMS params are extracted and forwarded to
 * {@link StarionCommunicator} implementation for further processing.
 * 
 * @author makcro
 * 
 */
public class SmsRequestHandlerImpl implements HttpRequestHandler {

	/**
	 * Logger instance
	 */
	private Logger logger = Logger.getLogger(SmsRequestHandlerImpl.class);

	/**
	 * Enumeration of starion's sms parameters
	 * 
	 */
	public enum StarionSmsParams {
		MSG_ID("msg_id"), MSISDN("msisdn"), MESSAGE("message"), OPERATOR("operator"), SHORT_ID("short_id"), PROVIDER("provider"), SDP("sdp");

		private StarionSmsParams(String name) {
			this.name = name;
		}

		private String name;

		public String getName() {
			return name;
		}
	}

	/**
	 * Communicator instance responsible for sms processing
	 */
	private StarionCommunicator starionCommunicator = null;

	/**
	 * Extracts SMS parameters from HTTP request and forwards them to {@link StarionCommunicator}
	 */
	@Override
	public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// extract paramters
		String messageText = request.getParameter(StarionSmsParams.MESSAGE.getName());
		String starionMessageId = request.getParameter(StarionSmsParams.MSG_ID.getName());
		String senderId = request.getParameter(StarionSmsParams.MSISDN.getName());
		String operator = request.getParameter(StarionSmsParams.OPERATOR.getName());
		String providerId = request.getParameter(StarionSmsParams.PROVIDER.getName());
		String sdp = request.getParameter(StarionSmsParams.SDP.getName());
		String shortId = request.getParameter(StarionSmsParams.SHORT_ID.getName());
		
		logger.info(MessageFormat.format("Successfully received new sms request, message id = [{0}], text = [{1}]", starionMessageId, messageText));
		
		this.starionCommunicator.onSmsMessage(senderId, shortId, providerId, messageText, starionMessageId, sdp, operator);
		
		
	}

	public void setStarionCommunicator(StarionCommunicator starionCommunicator) {
		this.starionCommunicator = starionCommunicator;
	}

}
